package de.htw.praxisprojekt;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.List;

import javax.swing.JPanel;

import de.htw.praxisprojekt.data.AlgoPoint;
import de.htw.praxisprojekt.data.draw.DrawObject;

public class DrawPanel extends JPanel implements MouseListener,MouseMotionListener{

	private List<DrawObject> drawObjects;
	private LineAlgo lineAlgo;
	/** The active algo point **/
	private AlgoPoint activeAlgoPoint=null;

	public DrawPanel(LineAlgo lineAlgo){
		this.lineAlgo=lineAlgo;
		this.drawObjects=lineAlgo.getAlgoData().getDrawObjects();
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
	}

	@Override
	protected void paintComponent(Graphics g){
		super.paintComponent(g);
		Graphics2D g2d=(Graphics2D)g;
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setColor(Color.WHITE);
		g2d.fillRect(0,0,g2d.getClipBounds().width,g2d.getClipBounds().height);
		for(int i=0;i<drawObjects.size();++i)
			drawObjects.get(i).draw(g2d);
	}

	@Override
	public void mousePressed(MouseEvent e){
		int button=e.getButton();
		if(button==MouseEvent.BUTTON1){
			int clickRadius=5;
			int mouseX=e.getX();
			int mouseY=getBounds().height-e.getY();
			List<AlgoPoint> algoPoints=lineAlgo.getAlgoData().getAlgoPoints();
			for(int i=0;i<algoPoints.size();++i){
				Vector2D point=algoPoints.get(i).getPoint();
				Rectangle rectangle=new Rectangle(point.getX()-clickRadius,point.getY()-clickRadius,clickRadius*2+1,clickRadius*2+1);
				if(rectangle.contains(mouseX,mouseY)){
					activeAlgoPoint=algoPoints.get(i);
					this.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
				}
			}
		}
	}

	@Override
	public void mouseReleased(MouseEvent e){
		activeAlgoPoint=null;
		this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	@Override
	public void mouseEntered(MouseEvent e){
	}

	@Override
	public void mouseExited(MouseEvent e){
	}

	@Override
	public void mouseClicked(MouseEvent e){
		if(e.getButton()==MouseEvent.BUTTON3){
			Vector2D point=new Vector2D(e.getX(),getBounds().height-e.getY());
			lineAlgo.getAlgoData().getAlgoPoints().add(new AlgoPoint(point.x,point.y));
			lineAlgo.redrawBasic();
			lineAlgo.changeComponentBehavior();
		}
	}

	@Override
	public void mouseDragged(MouseEvent e){
		if(activeAlgoPoint!=null){
			int mouseX=e.getX();
			int mouseY=getBounds().height-e.getY();
			activeAlgoPoint.getPoint().set(mouseX,mouseY);
			lineAlgo.redrawBasic();
		}
	}

	@Override
	public void mouseMoved(MouseEvent e){
	}
}